package com.shangjinrong.controller.site;

import com.alibaba.fastjson.JSON;
import com.shangjinrong.domain.LendItem;
import com.shangjinrong.domain.vo.InvestVO;
import com.shangjinrong.hfb.RequestHelper;
import com.shangjinrong.result.R;
import com.shangjinrong.service.LendItemService;
import com.shangjinrong.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author Naruto
 */


@RestController
@CrossOrigin
@Slf4j
@RequestMapping("site/lendItem")
public class SiteLendItemController {
    @Autowired
    private LendItemService lendItemService;

    /**
     * 根据标的id返回该标的的所有投资列表
     *
     * @param lendId 标的id
     * @return 返回该标的的投资列表
     */
    @GetMapping("list/{lendId}")
    public R list(@PathVariable Long lendId) {
        List<LendItem> lendItemList = lendItemService.selectByLendId(lendId);
        return R.ok().data("lendItemList", lendItemList);
    }
    //会员投资提交数据
    @PostMapping("auth/commitInvest")
    public R commitInvest(@RequestBody InvestVO investVO, HttpServletRequest request) {

        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String userName = JwtUtils.getUserName(token);
        investVO.setInvestUserId(userId);
        investVO.setInvestName(userName);

        //构建充值自动提交表单
        String formStr = lendItemService.commitInvest(investVO);
        return R.ok().data("formStr", formStr);
    }
    @GetMapping("select")
    public R selectByUserId(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        List<LendItem> lendItems = lendItemService.selectByUserId(userId);
        return R.ok().data("lendItems",lendItems);
    }

    @PostMapping("notify")
    public String notify(HttpServletRequest request) {

        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("用户投资异步回调：" + JSON.toJSONString(paramMap));

        //校验签名 P2pInvestNotifyVo
        if(RequestHelper.isSignEquals(paramMap)) {
            if("0001".equals(paramMap.get("resultCode"))) {
                lendItemService.notify(paramMap);
            } else {
                log.info("用户投资异步回调失败：" + JSON.toJSONString(paramMap));
                return "fail";
            }
        } else {
            log.info("用户投资异步回调签名错误：" + JSON.toJSONString(paramMap));
            return "fail";
        }
        return "success";
    }




}
